import React from "react";
import { Table, Radio, Icon, Popover, Row, Col, Modal, Tabs, message, Badge } from "antd";
const TabPane = Tabs.TabPane;
import { messages, simplifyDataSource } from "share/common";
import UserMale from "images/user-male.png";
import UserFemale from "images/user-female.png";
import UserUnknow from "images/user-unknow.png";
import PIDService from "containers/enterprise-manage/person-manage/person-info-display/person-info-display.service";
import constants from "share/constants";
import baseService from "share/base.service";
import creditViewService from "../../../credit/credit-view/credit-view.service";
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
import "styles/enterprise-manage/person-manage/employee-info/employee-info.scss";
import moment from "moment";
import ResizeTable from "components/resize-table";

class EmployeeInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      basicInfo: { userJobsDTOs: [], documentUserJob: {} },
      activeKey: "position",
      tableLoading: false,
      pagination: {
        pageSize: 5,
        total: 0,
      },
      operationType: undefined,
      data: [],
      page: 0,
      size: 5,
      creditInfo: {},
      defaultShowCredit: false,
      defaultShowJob: false,
      defaultBasicInfoFields: [
        { label: messages("common.user.id") /*工号*/, value: "employeeID" },
        { label: messages("common-1.key561") /*性别*/, value: "gender" },
        { label: messages("common-1.key560") /*人员类型*/, value: "employeeType" },
        { label: messages("common-1.key563") /*入职时间*/, value: "entryDate" },
        { label: messages("common-1.key559") /*直属领导*/, value: "directManager" },
        { label: messages("common-1.key243") /*手机*/, value: "mobile" },
        { label: messages("common-1.key244") /*邮箱*/, value: "email" },
      ],
      defaultPositionInfoFields: [
        { label: messages("basic-5.key1") /*公司*/, value: "company", width: 120 },
        { label: messages("common.department") /*部门*/, value: "department", width: 120 },
        { label: messages("basic-5.key163") /*职位*/, value: "title", width: 120 },
        { label: messages("basic-5.key279") /*职务*/, value: "duty", width: 120 },
        { label: messages("basic-5.key280") /*级别*/, value: "rank", width: 120 },
        { label: messages("basic-5.key412") /*主岗*/, value: "companyMainPosition", width: 120 },
      ],
    };
    this.creditColumns = this.renderCreditColumns();
    this.userImg = {
      0: UserMale,
      1: UserFemale,
      2: UserUnknow,
    };
  }

  componentDidMount() {
    this.getBasicInfo();
    this.getUser();
    this.getList();
    this.getFormSetting();
    if (this.props.activeKey) {
      this.setState({
        activeKey: this.props.activeKey,
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.activeKey) {
      if (
        (this.props.showJob === false && nextProps.showJob) ||
        (nextProps.showJob && nextProps.showCredit === false)
      ) {
        this.setState({
          activeKey: "position",
        });
      }
      if (
        (nextProps.showCredit && this.props.showCredit === false) ||
        (nextProps.showCredit && nextProps.showJob === false)
      ) {
        this.setState({
          activeKey: "credit",
        });
      }
    }
  }

  getFormSetting = () => {
    const { defaultBasicInfoFields, defaultPositionInfoFields } = this.state;
    PIDService.getFormSetting()
      .then((res) => {
        let setting = res.data;
        let arr = defaultBasicInfoFields.filter((item) => setting[item.value]);
        let arr2 = defaultPositionInfoFields.filter((item) => setting[item.value]);
        this.setState({
          defaultBasicInfoFields: arr,
          defaultPositionInfoFields: arr2,
          defaultShowCredit: setting.credit,
          defaultShowJob: setting.job,
        });
      })
      .catch((err) => {});
  };

  getBasicInfo = () => {
    const { userOID, jobId } = this.props.params;
    PIDService.getBasicInfo(userOID, jobId)
      .then((res) => {
        this.setState({
          basicInfo: res.data,
        });
      })
      .catch((err) => {});
  };

  onTabClick = (activeKey) => {
    this.setState({
      activeKey,
    });
  };

  renderCreditColumns = () => {
    let source = [
      { businessCode: messages("common-1.key352") /*相关单据*/ },
      { comment: messages("common-1.key353") /*事件描叙*/ },
      { ruleCondition: messages("common-1.key354") /*信用规则*/ },
      {
        modelTypeId: messages("common-1.key355") /*信用类型*/,
        render: (value) => {
          let res = "-";
          switch (value) {
            case 1001:
              res = messages("common-1.key356") /*报销信用*/;
              break;
            default:
              res = messages("common-1.key357") /*审批信用*/;
              break;
          }
          return res;
        },
      },
      {
        operationType: messages("common-1.key358") /*处理方式*/,
        render: (value) => {
          let res = "-";
          switch (value) {
            case 1001:
              res = messages("common-1.key359") /*加分*/;
              break;
            case 1002:
              res = messages("common-1.key360") /*减分*/;
              break;
            case 1003:
              res = messages("common-1.key361") /*升级*/;
              break;
            default:
              res = messages("common-1.key362") /*降级*/;
              break;
          }
          return res;
        },
      },
      {
        change: messages("common-1.key363") /*处理结果*/,
        render: (value, record) => {
          let res = "-";
          switch (record.operationType) {
            case 1001:
              res = `${record.changeScore}`;
              break;
            case 1002:
              res = `-${record.changeScore}`;
              break;
            case 1003:
              res = `${record.changeRank}`;
              break;
            default:
              res = `-${record.changeRank}`;
              break;
          }
          return res;
        },
      },
      {
        lastModifiedDate: messages("common-1.key364") /*更新时间*/,
        render: (value) => new Date(value).format("yyyy-MM-dd"),
        width: 120,
      },
      {
        status: messages("common.column.status") /*状态*/,
        fixed: "right",
        render: (value) => {
          let temp = value === 1001;
          return (
            <Badge
              status={temp ? "success" : "error"}
              text={temp ? messages("common-1.key28") /*启用temp*/ : messages("common.reject") /*驳回*/}
            />
          );
        },
      },
    ];
    return simplifyDataSource(source);
  };

  getUser = () => {
    const { jobId } = this.props.params;
    this.setState({ userLoading: true });
    creditViewService.getUserCreditInfo(jobId ? { jobId } : {}).then((res) => {
      this.setState({ creditInfo: res.data, userLoading: false });
    });
  };

  getList = () => {
    const { page, size, operationType } = this.state;
    const { userOID, jobId } = this.props.params;
    let params = { userOID, page, size };
    jobId && (params.jobId = jobId);
    operationType && (params.operationType = operationType);
    this.setState({ tableLoading: true });
    baseService
      .getHonestHistory(params)
      .then((res) => {
        this.setState({
          data: res.data,
          tableLoading: false,
          pagination: {
            pageSize: 5,
            total: Number(res.headers["x-total-count"]),
            onChange: this.onChangePager,
            current: this.state.page + 1,
          },
        });
      })
      .catch((e) => {
        this.setState({ tableLoading: false });
        message.error(e.response.data.message);
      });
  };

  handleChangeRadio = (e) => {
    this.setState({ operationType: e.target.value, page: 0 }, this.getList);
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page) this.setState({ page: page - 1 }, this.getList);
  };

  render() {
    const {
      activeKey,
      tableLoading,
      data,
      pagination,
      creditInfo,
      basicInfo,
      defaultShowCredit,
      defaultShowJob,
      defaultBasicInfoFields,
      defaultPositionInfoFields,
    } = this.state;
    const { basicInfoFields, showJob, tabs, positionInfoFields, showCredit, positionChangeDate } = this.props;
    const credit = showCredit === undefined ? defaultShowCredit : showCredit;
    const job = showJob === undefined ? defaultShowJob : showJob;
    const special = {
      entryDate: "entryTime",
      directManager: "directManagerName",
      company: "companyName",
      department: "departmentName",
      title: "position",
    };
    const positionCol = (positionInfoFields || defaultPositionInfoFields).map((item) => {
      return {
        title: item.label,
        dataIndex: special[item.value] || item.value,
        render: (text) => {
          return item.value === "companyMainPosition" ? (
            text ? (
              messages("common.yes") /*是*/
            ) : (
              messages("common.no")
            ) /*否*/
          ) : (
            <Popover content={text}>{text}</Popover>
          );
        },
      };
    });
    let date = basicInfo.documentUserJob
      ? basicInfo.documentUserJob.lastModifiedDate
      : basicInfo.userJobsDTOs
      ? (basicInfo.userJobsDTOs[0] || {}).lastModifiedDate
      : null;
    return (
      <div className="employee-info-wrap">
        <div className="employee-info-left-wrap">
          <div className="employee-info-img">
            <span>
              <img src={basicInfo.avatar || this.userImg[basicInfo.genderCode || 2]} className="employee-info-avatar" />
            </span>
            <span className="employee-info-name">{basicInfo.fullName}</span>
            {(basicInfo.status === 1002 || basicInfo.status === 1003) && (
              <span className="employee-info-quit">
                {
                  basicInfo.status === 1002
                    ? messages("common-1.key572") /*即将离职*/
                    : messages("common-1.key967") /*已离职*/
                }
              </span>
            )}
          </div>
          <div className="basic-info-title">{messages("common.baseInfo") /*基本信息*/}</div>
          {(basicInfoFields || defaultBasicInfoFields).map((item) => {
            return (
              <div className="top-gap text-ellipsis">
                <span className="basic-info-label">{item.label}：</span>
                <span className="basic-info-value">
                  {item.value === "entryDate" && basicInfo.entryTime
                    ? moment(basicInfo.entryTime).format("YYYY-MM-DD")
                    : item.value === "directManager"
                    ? basicInfo.directManagerName
                    : basicInfo[item.value] || "-"}
                </span>
              </div>
            );
          })}
        </div>
        <div className="employee-info-right-wrap">
          {(job || credit || !!tabs.length) && (
            <Tabs activeKey={activeKey} onTabClick={this.onTabClick}>
              {job && (
                <TabPane tab={messages("common-1.key433") /*岗位*/} key="position">
                  <div className="employee-info-tab-content bottom-gap">
                    <div className="basic-info-title bottom-gap">
                      {messages("basic-5.key921") /*单据岗位*/}
                      {date && positionChangeDate && (
                        <span className="left-gap position-change-info">
                          {
                            messages("basic-5.key982", {
                              arg1: moment(date).format("YYYY-MM-DD"),
                            }) /*该岗位已于{arg1}变更*/
                          }
                        </span>
                      )}
                    </div>
                    <ResizeTable
                      rowKey="id"
                      columns={positionCol}
                      dataSource={
                        basicInfo.documentUserJob
                          ? [basicInfo.documentUserJob || {}]
                          : basicInfo.userJobsDTOs
                          ? [basicInfo.userJobsDTOs[0] || {}]
                          : []
                      }
                      pagination={false}
                      bordered
                    />
                    <div className="basic-info-title inline-gap">{messages("basic-5.key922") /*全部岗位*/}</div>
                    <ResizeTable
                      rowKey="id"
                      columns={positionCol}
                      dataSource={basicInfo.userJobsDTOs || []}
                      pagination={false}
                      bordered
                    />
                  </div>
                </TabPane>
              )}
              {credit && (
                <TabPane tab={messages("basic-3.key61") /*信用*/} key="credit">
                  <div className="employee-info-tab-content bottom-gap">
                    <div className="high-gap">
                      <div className="basic-info-title bottom-gap">{messages("basic-5.key923") /*当前信用*/}</div>
                      <Row>
                        {[
                          { label: messages("finance-3.key40") /*信用分*/, key: "score" },
                          { label: messages("finance-3.key41") /*信用等级*/, key: "creditRank" },
                          { label: messages("finance-3.key42") /*等级说明*/, key: "rankComment" },
                        ].map((item) => {
                          return (
                            <Col span={8}>
                              <span className="basic-info-label">{item.label}：</span>
                              <span className="basic-info-value">{creditInfo[item.key] || "-"}</span>
                            </Col>
                          );
                        })}
                      </Row>
                    </div>
                    <div className="basic-info-title">{messages("common-1.key224") /*信用事件*/}</div>
                    <div className="table-title inline-gap">
                      <RadioGroup defaultValue={undefined} onChange={this.handleChangeRadio}>
                        <RadioButton value={undefined}>{messages("common.all") /*全部*/}</RadioButton>
                        {constants.creditRuleOperation.map((item) => (
                          <RadioButton value={item.value} key={item.value}>
                            {item.text}
                          </RadioButton>
                        ))}
                      </RadioGroup>
                    </div>
                    <div className="credit-table-wrap">
                      <div className="credit-table-inside-wrap">
                        <ResizeTable
                          bordered
                          dataSource={data}
                          pagination={pagination}
                          columns={this.creditColumns}
                          rowKey="id"
                          loading={tableLoading}
                        />
                      </div>
                    </div>
                  </div>
                </TabPane>
              )}
              {tabs.length
                ? tabs.map((item) => {
                    return (
                      <TabPane tab={item.name} key={item.key}>
                        {item.component}
                      </TabPane>
                    );
                  })
                : null}
            </Tabs>
          )}
        </div>
      </div>
    );
  }
}

EmployeeInfo.propTypes = {
  basicInfoFields: React.PropTypes.array,
  positionInfoFields: React.PropTypes.array,
  showCredit: React.PropTypes.bool,
  visible: React.PropTypes.bool,
  tabs: React.PropTypes.array,
  activeKey: React.PropTypes.string,
  positionChangeDate: React.PropTypes.bool,
};

EmployeeInfo.defaultProps = {
  showCredit: undefined,
  visible: false,
  tabs: [], //[{name: "岗位", key: "position", component: <EmployeeInfo/>}]
  activeKey: "position",
  positionChangeDate: true,
};
export default EmployeeInfo;
